package dragon

import (
	"fmt"
	"http"
	"json"
	"template"
	"strconv"

	"appengine"
	"appengine/urlfetch"
)

const photosFeed = `http://picasaweb.google.com/data/feed/api/user/%s/albumid/%s?alt=%s&v=%s&thumbsize=%s&imgmax=%s&fields=%s`

type photo struct {
	Id string
	Thumb string
	Img string
	Width string
	Height string
}

func handlePhotos(w http.ResponseWriter, r *http.Request) {
	const lenPath = len(photosURL)
	const fields = "entry(gphoto:id,media:group(media:thumbnail,media:content))"
	const albumidlen = 19

	c := appengine.NewContext(r)
	client := urlfetch.Client(c)

	albumid := r.URL.Path[lenPath:]
	if len(albumid) != albumidlen || !isAllDigits(albumid) {
		http.Redirect(w, r, albumspageURL, http.StatusFound)
		return
	}
	tmpURL := fmt.Sprintf(photosFeed, user, albumid,
		method, apiver, thumbsize, imgmax, fields)
	resp, _ := client.Get(tmpURL)

	p := make([]photo, 10)
	var d data

	dec := json.NewDecoder(resp.Body)
	dec.Decode(&d)
	resp.Body.Close()

	p = getPhotos(&d, p)

	ts := new(template.Set)
        troot, _ := template.New("root").
		Funcs(template.FuncMap{
			"date": stuffDate,
		}).
		ParseFile("templates/root.html")
        tcontent, _ := template.New("content").
		ParseFile("templates/photos.html")
        ts.Add(troot, tcontent)
        ts.Execute(w, "root", map[string]interface{}{"Photos": p, "Site": count(c, r, w),})
}

func getPhotos(d *data, p []photo) []photo {
    var k int

	for k = range d.Feed.Entry {
		if k+1 >= cap(p) {
                        np := make([]photo, k*2)
                        copy(np, p)
                        p = np
                }
		var tmp interface{}

		tmp = d.Feed.Entry[k]["gphoto$id"]
		p[k].Id = tmp.(map[string]interface{})["$t"].(string)

		tmp = d.Feed.Entry[k]["media$group"]
		p[k].Thumb = tmp.(map[string]interface{})["media$thumbnail"].(
				[]interface{})[0].(
				map[string]interface{})["url"].(string)
		p[k].Width = strconv.Ftoa64(tmp.(map[string]interface{})["media$thumbnail"].(
				[]interface{})[0].(
				map[string]interface{})["width"].(float64), 'f', 0)
		p[k].Height = strconv.Ftoa64(tmp.(map[string]interface{})["media$thumbnail"].(
				[]interface{})[0].(
				map[string]interface{})["height"].(float64), 'f', 0)

		tmp = d.Feed.Entry[k]["media$group"]
		p[k].Img = tmp.(map[string]interface{})["media$content"].(
				[]interface{})[0].(
				map[string]interface{})["url"].(string)
	}
	p = p[0:k+1]

	return p
}
